import router from './router'
import { useAppStoreWithOut } from '@/store/modules/app'
import type { RouteRecordRaw } from 'vue-router'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { NO_REDIRECT_WHITE_LIST } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { getAdminRoleApi, getTestRoleApi } from '@/api/login'

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

router.beforeEach(async (to, from, next) => {
  start()
  loadStart()
  const permissionStore = usePermissionStoreWithOut()
  const appStore = useAppStoreWithOut()
  const userStore = useUserStoreWithOut()
  if (userStore.getUserInfo) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      const roleRouters = userStore.getRoleRouters || []

      if (!roleRouters.length) {
        // 是否使用动态路由
        if (appStore.getDynamicRouter && appStore.getServerDynamicRouter) {
          try {
            const resp = await getAdminRoleApi({})
            if (resp.data && resp.data.length) {
              const routers = resp.data || []
              userStore.setRoleRouters(routers)
              await permissionStore.generateRoutes('server', routers as AppCustomRouteRecordRaw[])
              permissionStore.getAddRouters.forEach((route) => {
                router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
              })
              permissionStore.setIsAddRouters(true)
              next({ ...to, replace: true })
            } else {
              await Promise.reject(
                new Error('当前账号接口获取菜单出现异常，请重新登录或联系管理员。')
              )
            }
          } catch (e) {
            ElMessage.error('当前账号接口获取菜单出现异常，请重新登录或联系管理员。')
            userStore.signOut()
            next({ path: '/login', query: { ...{ redirect: to.path }, ...to.query } })
            done()
            loadDone()
          }
        }
      } else {
        next()
      }
    }
  } else {
    if (NO_REDIRECT_WHITE_LIST.indexOf(to.path) !== -1) {
      next()
    } else {
      next({ path: '/login', query: { ...{ redirect: to.path }, ...to.query } }) // 否则全部重定向到登录页
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
